package threads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class FixedCntBoxTest_ReentrantLock<T> {
    private volatile int count;
    private static final int MAX_CNT = 10;
    private final List<T> list = new ArrayList<>();
    private ReentrantLock lock = new ReentrantLock();
    private Condition putCondition = lock.newCondition();
    private Condition getCondition = lock.newCondition();

    public void put(T t) {
        try {
            lock.lock();
            while (count >= MAX_CNT) {
                try {
                    putCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count++;
            list.add(t);
            getCondition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public T get() {
        try {
            lock.lock();
            while (count <= 0) {
                try {
                    getCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count--;
            T t = list.remove(list.size() - 1);
            putCondition.signalAll();
            return t;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        FixedCntBoxTest_ReentrantLock<String> list = new FixedCntBoxTest_ReentrantLock<>();
        for (int i = 0; i < 1; i++) {
            new Thread(() -> {
                while (true) {
                    String s = list.get();
                    System.out.println(Thread.currentThread().getName() + "消费:" + s);
                }
            }, "消费者" + i).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                int cnt = 0;
                while (true) {
                    String tName = Thread.currentThread().getName();
                    String pName = tName + "产品" + (cnt++);
                    list.put(pName);
                    System.out.println("生产者" + tName + "生产产品：" + pName);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "t" + i).start();
        }
    }
}
